#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
@File    :  temp_cmd_download.py
@Time    :  2022/05/23 15:19:25
@Author  :  HHLiang
@Contact :  sternapeg@qq.com
@Version :  1.0
@Desc    :  平台命令下发及获取系统运行命令
'''

# import ctypes
# import sys

from edp_sdk import *
from config import config_run
from temp_DAQ_upload import get_CPU_Temp


# def is_admin():
#     try:
#         return ctypes.windll.shell32.IsUserAnAdmin()
#     except:
#         return False

# if is_admin():
#     # Code of your program here
#     # 读取温度
#     print("获取电脑CPU温度!")
#     cpu_temp = get_CPU_Temp()
#     # print(cpu_temp)
# else:
#     # Re-run the program with admin rights
#     ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__, None, 1)


if __name__ == '__main__':

    # 以下设备和产品信息，请自行补全
    # api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'    # 设备APIkey
    # product_id = 'XXXXXX'                       # 产品ID
    # device_id = 'XXXXXXXXX'                     # 设备ID
    # auth_info = 'XXXXXXXXXXXX'                  # 鉴权信息
    config = config_run('A1')

    api_key = config[0]
    product_id = config[1]
    device_id = config[2]
    auth_info = config[3]

    host = config[4]
    port = config[5]

    # 创建Sockey连接
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 建立连接
    s.connect((host, port))
    # 发送登录报文， 并接收响应
    conn_msg = gen_conn_msg(pid=product_id, auth_info=auth_info)
    print(conn_msg)
    s.send(conn_msg)
    # 接收响应并打印
    resp = s.recv(1024)
    print('设备注册结果：', resp)

    # 循环，定时接收命令
    while True:
        # 接收平台信息
        recv_data = s.recv(1024)
        print(recv_data)
        # 解析平台信息
        res = recv_data_parser(recv_data)
        if res:
            cmd_id, cmd_body = res
            print('cmd_id: ', cmd_id)
            print('cmd_body: ', cmd_body)

            ''' 自定义功能实现 '''
            # 当命令为1时，打印turn on
            if cmd_body == b'1':
                # 获取电脑CPU温度
                cpu_temp = get_CPU_Temp()
                # 获取时间
                t = time.strftime("%Y-%m-%d %H:%M:%S")
                print("获取电脑CPU温度: ", cpu_temp)
                print("开始上传数据！")
                data = {'temp': {t: cpu_temp}}
                print(data)
                # 以数据类型四进行组包并发送数据
                t4_data = save_type4(json.dumps(data), 1)
                # 上传数据到云平台
                s.send(t4_data)
                print('data: ', t4_data)
                # 接收反馈信息并打印
                resp = s.recv(1024)
                print('recv: ', resp)

            elif cmd_body == b'0':
                break
            # 其他命令，打印turn off~
            else:
                print('other')
            # 发送反馈
            s.send(cmd_reply(cmd_id, 'command response'.encode()))
            check_cmd_resp(cmd_id, api_key)
        # 定时
        time.sleep(5)
